package com.appology.mail;

import java.io.IOException;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.appology.users.ChuckUser;
import com.appology.users.ChuckUserHelper;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

import java.util.Date;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class SendEmail extends HttpServlet {

	private static final long serialVersionUID = 1L;
	private static final String JON_EMAIL = "jonfhancock@gmail.com";
	private static final String JON_NAME = "Jon";
	private static final String CRAIG_EMAIL = "craigmersereau@gmail.com";
	private static final String CRAIG_NAME = "Craig";
	private static final String BRANDT_EMAIL = "brandtdaniels@gmail.com";
	private static final String BRANDT_NAME = "Brandt";
	private static final String FERDIE_EMAIL = "ferneugenio@gmail.com";
	private static final String FERDIE_NAME = "Ferdie";
	private static final String DEFAULT_SUBJECT = "Thanks for making such an awesome app!";
	private static final String PARAMETER_BODY = "body";
	private static final String PARAMETER_SUBJECT = "subject";
	private static final String SUCCESS_MESSAGE = "success";
	private static final String NO_BODY_MESSAGE = "noBody";
	private static final String NOT_LOGGED_IN_MESSAGE = "notLoggedIn";

	private static InternetAddress jon;
	private static InternetAddress[] ccAddresses;
	private static UserService userService;
	private static User user;
	private static ChuckUser chuckUser;
	private static String subject = DEFAULT_SUBJECT;
	private static String body = null;
	private static String name;
	private static Properties props;
	private static Session session;
	private static Message msg;

	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {

		// Set the content type as text/plain, and set the headers to explicitly
		// disallow caching in the browser. We always want a fresh copy of
		// whatever this page has to say
		resp.setContentType("text/plain");
		resp.setHeader("Expires", "Tue, 03 Jul 2001 06:00:00 GMT");
		resp.setHeader("Last-Modified", new Date().toString());
		resp.setHeader("Cache-Control",
				"no-store, no-cache, must-revalidate, max-age=0, post-check=0, pre-check=0");
		resp.setHeader("Pragma", "no-cache");

		// Instantiate all of our recipients
		jon = new InternetAddress(JON_EMAIL, JON_NAME);
		ccAddresses = new InternetAddress[] {
				new InternetAddress(CRAIG_EMAIL, CRAIG_NAME),
				new InternetAddress(BRANDT_EMAIL, BRANDT_NAME),
				new InternetAddress(FERDIE_EMAIL, FERDIE_NAME), };

		// Get the current Google user making the request
		userService = UserServiceFactory.getUserService();
		user = userService.getCurrentUser();

		// Only proceed if the user is not null. Otherwise, ask them to log in.
		if (user != null) {

			// Try to get the corresponding ChuckUser so we can get a nice
			// display name.
			// If we can't then just use the Google username.
			chuckUser = ChuckUserHelper
					.getChuckUserByGoogleId(user.getUserId());
			if (chuckUser != null && chuckUser.getDisplayName() != null) {
				name = chuckUser.getDisplayName();
			} else {
				name = user.getNickname();
			}

			// Only proccede from this point if the user has provided a non
			// empty body for the email
			// If they left out the body, send back an error message saying so
			if (req.getParameter(PARAMETER_BODY) != null
					&& !req.getParameter(PARAMETER_BODY).trim().equals("")) {

				// The subject is optional because we have specified a default
				// subject
				// If the user didn't provide a subject, use the default one.
				if (req.getParameter(PARAMETER_SUBJECT) != null) {
					subject = req.getParameter(PARAMETER_SUBJECT);
				}

				// Set the body of the email
				body = req.getParameter(PARAMETER_BODY);

				// Get a new Properties object for our session
				props = new Properties();

				// Get a new Session for our Message object
				session = Session.getDefaultInstance(props, null);

				// Try to build and send the email
				try {
					// Instantiate our Message object
					msg = new MimeMessage(session);

					// Set the from address to our currently logged in user.
					// Use either the display name we have on file, or their
					// Google username
					msg.setFrom(new InternetAddress(user.getEmail(), name));

					// Add the primary recipient
					msg.addRecipient(Message.RecipientType.TO, jon);

					// Add an array of recipients to be CC'd
					msg.addRecipients(Message.RecipientType.CC, ccAddresses);

					// Add the subject
					msg.setSubject(subject);

					// Add the body
					msg.setText(body);

					// Send the email
					Transport.send(msg);
				} catch (AddressException e) {
					// ...
				} catch (MessagingException e) {
					// ...
				}

				// Only send the success message back if the email was
				// successfully sent
				resp.getWriter().print(SUCCESS_MESSAGE);
			} else {

				// Send back an error message if there was no body provided
				resp.getWriter().print(NO_BODY_MESSAGE);
			}

		} else {

			// Send back an error message if the user is not logged in
			resp.getWriter().print(NOT_LOGGED_IN_MESSAGE);

		}

	}

}
